#include "ThreadPool.hpp"
#include "Thread.hpp"
#include "WorkerThread.hpp"

#include <unistd.h>
#include <stdio.h>


namespace wd{

using Elemtype = std::function<void()>;

ThreadPool::ThreadPool(int threadnum, int quesize)
:_threads()
,_threadNum(threadnum)
,_queSize(quesize)
,_taskque(_queSize)
,_isExit(false)
{}

void ThreadPool::start(){
    //创建线程
    for(int i = 0; i< _threadNum; ++i){
        unique_ptr<Thread> up(new WorkerThread(*this));
        _threads.push_back(std::move(up));
    }
    //启动线程
    for(auto & th : _threads){
        th->start();
    }
}

void ThreadPool::stop(){
    while(! _taskque.empty()){
        sleep(1);
    }
    
    _isExit = true;    
    _taskque.wakeup();  //解除pop函数的阻塞

    printf("after wakeup \n");
    for(auto & th : _threads){
        th->join();
    }
}

void ThreadPool::addTask(Elemtype && ele){
    _taskque.push(std::move(ele));
}

void ThreadPool::doTask(){
    while(!_isExit){

        Elemtype ele = _taskque.pop();
        if(ele){
            ele();
        }
    }
    
}}
